<?php

namespace addons\library;

use think\facade\Hook;
use think\App;
use think\Container;
use think\Loader;
use think\facade\Config;
use think\Request;

/**
 * 插件执行默认控制器
 *
 * @package think\addons
 */
class Route
{
    protected $request;

    public function __construct(App $app, Request $request, $controller = '')
    {
        $this->app = $app;
        $this->request = $request;

        // 处理路由参数
        $route = [
            $this->request->param('addon'),
            $this->request->param('controller'),
            $this->request->param('action'),
        ];
        // 是否自动转换控制器和操作名
        $convert = Config::get('app.url_convert');
        // 格式化路由的插件位置
        $this->action = $convert ? strtolower(array_pop($route)) : array_pop($route);
        $this->controller = $convert ? strtolower(array_pop($route)) : array_pop($route);
        $this->addon = $convert ? strtolower(array_pop($route)) : array_pop($route);
        // 生成view_path
        $view_path = ADDON_PATH . $this->addon . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
        // 重置配置
        config('template.view_path', $view_path);
        $this->request->setController($this->controller);
        $this->request->setAction($this->action);
        $class = $app->parseClass($this->addon, 'controller', $this->controller);
    }

    /**
     * 插件执行
     */
    public function execute()
    {

        if (!empty($this->addon) && !empty($this->controller) && !empty($this->action)) {
            // 获取类的命名空间
            $class = get_addon_class($this->addon, 'controller', $this->controller);
            if (class_exists($class)) {
                return $this->app->invokeMethod([$class, $this->action]);
            } else {
                abort(500, lang('Controller Class Not Exists'));
            }
        }
        abort(500, lang('addon cannot name or action'));
    }


}
